package org.prism.reflection;

import org.junit.Test;
import org.prism.reflection.bean.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Random;

public class ReflectionTest {

    @Test
    public void test1(){
        Person person = new Person(1001, "张三", 10, "男");
        person.setAge(22);
        person.sayHello("李四");
        System.out.println("person = " + person);
    }
    //调用public构造器
    @Test
    public void test2() throws Exception {
        Class<Person> pClass = Person.class;
        Constructor<Person> cons = pClass.getConstructor(Integer.class, String.class, Integer.class, String.class);
        Person person = cons.newInstance(1002, "李四", 23, "女");
        System.out.println("person = " + person);
        Method show = pClass.getDeclaredMethod("show");
        show.invoke(person);
        Method sayHello = pClass.getDeclaredMethod("sayHello",String.class);
        sayHello.invoke(person,"王朋龙");

        //调用私有结构
        Constructor<Person> cons1 = pClass.getDeclaredConstructor(String.class);
        cons1.setAccessible(true);
        Person person1 = cons1.newInstance("张三丰");
        System.out.println("person1 = " + person1);
        Field sex = pClass.getDeclaredField("sex");
        sex.setAccessible(true);
        sex.set(person1,"女");
        System.out.println("person1 = " + person1);

        Method writeHello = pClass.getDeclaredMethod("writeHello", String.class);
        writeHello.setAccessible(true);
        Object invoke = writeHello.invoke(person1,"周芷若");
        System.out.println("invoke = " + invoke);
    }


    @Test
    public void test3() throws Exception {
        String className = "";
        for (int i = 0; i < 20; i++) {
            int a = new Random().nextInt(3);
            switch (a){
                case 0 :
                    className = "org.prism.reflection.bean.Person";
                    break;
                case 1:
                    className = "org.prism.reflection.KnowReflection";
                    break;
                case 2:
                    className = "org.prism.reflection.ReflectionTest";
                    break;
            }
            Object instance = getInstance(className);
            System.out.println("instance = " + instance);
        }
    }

    public Object getInstance(String className) throws Exception{
        Class<?> aClass = Class.forName(className);
        return aClass.newInstance();

    }


}
